/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sistemabienes;

import com.sun.data.provider.RowKey;
import com.sun.data.provider.impl.CachedRowSetDataProvider;
import com.sun.data.provider.impl.TableRowDataProvider;
import com.sun.rave.faces.converter.SqlDateConverter;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.sql.rowset.CachedRowSetXImpl;
import com.sun.webui.jsf.component.Button;
import com.sun.webui.jsf.component.Calendar;import com.sun.webui.jsf.component.Label;
import com.sun.webui.jsf.component.Listbox;
import com.sun.webui.jsf.component.Table;
import com.sun.webui.jsf.component.TableRowGroup;
import com.sun.webui.jsf.model.DefaultOptionsList;
import com.sun.webui.jsf.model.DefaultTableDataProvider;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.DateTimeConverter;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.LengthValidator;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.sun.webui.jsf.component.TextField;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.validator.ValidatorException;
import javax.naming.NamingException;
import javax.sql.DataSource;


/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version ufv.java
 * @version Created on 05-10-2010, 11:38:11 AM
 * @author luis
 */

public class ufv extends AbstractPageBean {
    private DefaultOptionsList listbox1DefaultOptions = new DefaultOptionsList();

    public DefaultOptionsList getListbox1DefaultOptions() {
        return listbox1DefaultOptions;
    }

    public void setListbox1DefaultOptions(DefaultOptionsList dol) {
        this.listbox1DefaultOptions = dol;
    }
    private Listbox listbox1 = new Listbox();

    public Listbox getListbox1() {
        return listbox1;
    }

    public void setListbox1(Listbox l) {
        this.listbox1 = l;
    }
    private CachedRowSetDataProvider empleadosDataProvider = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getEmpleadosDataProvider() {
        return empleadosDataProvider;
    }

    public void setEmpleadosDataProvider(CachedRowSetDataProvider crsdp) {
        this.empleadosDataProvider = crsdp;
    }

    public ufv() throws Exception {
       ////////habiltar para logueo
         boolean us=this.getSessionBean1().isloged();

        if(us==false)
        {
            throw new Exception("Permiso denegado");

        }

    }
    public String aux=null;
      private String d=new String();
   
      public void setEditar(String se){
       this.d=se;
      }
      public String getEditar(){
      return d;
      }
    private void _init() throws Exception {
        //table1.setVisible(false);
        List<String> list = new ArrayList<String>();
         list.add("1");
         list.add("2");

        java.util.Date fecha = new Date();
         label4.setText(new java.sql.Date(fecha.getTime()));
        ufvDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.ufvRowSet}"));
        listbox1DefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{});
        listbox1DefaultOptions.setSelectedValue("value");
        empleadosDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.empleadosRowSet1}"));
         
        //listbox1DefaultOptions.setOptions(new com.sun.webui.jsf.model.Option);


       /* ufvRowSet.setDataSourceName("java:comp/env/jdbc/ACTIVOS_FIJOS_Oracle");                                             //like ?
        ufvRowSet.setCommand("SELECT cod_ufv,valor_ufv,to_char(fecha,'DD-MM-YYYY') as fecha FROM ACTIVOS_FIJOS.UFV where fecha like ? order by cod_ufv asc");
       //activosRowSet.setString(1,"'13-10-2010'");
        // activosRowSet.setCommand("SELECT cod_ufv,valor_ufv,to_char(fecha,'DD-MM-YYYY') as fecha FROM ACTIVOS_FIJOS.UFV where fecha=to_date(?,'DD-MM-YYYY') order by cod_ufv asc");
        //activosRowSet.setDate(1,new java.sql.Date(fecha.getTime()));
        ufvRowSet.setString(1,"%");
        ufvRowSet.setTableName("ufv");
        ufvDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{ufv.activosRowSet}"));
        */
    }
        private CachedRowSetXImpl ufvRowSet = new CachedRowSetXImpl();

    public CachedRowSetXImpl getUfvRowSet() {
        return ufvRowSet;
    }

    public void setUfvRowSet(CachedRowSetXImpl crsxi) {
        this.ufvRowSet = crsxi;
    }
    /*private CachedRowSetDataProvider ufvDataProvider = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getUfvDataProvider() {
        return ufvDataProvider;
    }

    public void setUfvDataProvider(CachedRowSetDataProvider crsdp) {
        this.ufvDataProvider = crsdp;
    }*/
    ///////////

    private TextField txtufv = new TextField();

    public TextField getTxtufv() {
        return txtufv;
    }

    public void setTxtufv(TextField tf) {
        this.txtufv = tf;
    }
    private Calendar calendar1 = new Calendar();

    public Calendar getCalendar1() {
        return calendar1;
    }

    public void setCalendar1(Calendar c) {
        this.calendar1 = c;
    }
    
    private SqlDateConverter sqlDateConverter1 = new SqlDateConverter();

    public SqlDateConverter getSqlDateConverter1() {
        return sqlDateConverter1;
    }

    public void setSqlDateConverter1(SqlDateConverter sdc) {
        this.sqlDateConverter1 = sdc;
    }
    private DateTimeConverter dateTimeConverter1 = new DateTimeConverter();

    public DateTimeConverter getDateTimeConverter1() {
        return dateTimeConverter1;
    }

    public void setDateTimeConverter1(DateTimeConverter dtc) {
        this.dateTimeConverter1 = dtc;
    }
    private Calendar calendar2 = new Calendar();

    public Calendar getCalendar2() {
        return calendar2;
    }

    public void setCalendar2(Calendar c) {
        this.calendar2 = c;
    }
    private Button button1 = new Button();

    public Button getButton1() {
        return button1;
    }

    public void setButton1(Button b) {
        this.button1 = b;
    }
    private Button modifica = new Button();

    public Button getModifica() {
        return modifica;
    }

    public void setModifica(Button b) {
        this.modifica = b;
    }
    private LengthValidator lengthValidator1 = new LengthValidator();

    public LengthValidator getLengthValidator1() {
        return lengthValidator1;
    }

    public void setLengthValidator1(LengthValidator lv) {
        this.lengthValidator1 = lv;
    }
    
    private Label label4 = new Label();

    public Label getLabel4() {
        return label4;
    }

    public void setLabel4(Label l) {
        this.label4 = l;
    }
    private Button button3 = new Button();

    public Button getButton3() {
        return button3;
    }

    public void setButton3(Button b) {
        this.button3 = b;
    }
    private Label lblfecha = new Label();

    public Label getLblfecha() {
        return lblfecha;
    }

    public void setLblfecha(Label l) {
        this.lblfecha = l;
    }
    private Label prueba = new Label();

    public Label getPrueba() {
        return prueba;
    }

    public void setPrueba(Label l) {
        this.prueba = l;
    }
    private Table table1 = new Table();

    public Table getTable1() {
        return table1;
    }

    public void setTable1(Table t) {
        this.table1 = t;
    }
    private CachedRowSetDataProvider ufvDataProvider = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getUfvDataProvider() {
        return ufvDataProvider;
    }

    public void setUfvDataProvider(CachedRowSetDataProvider crsdp) {
        this.ufvDataProvider = crsdp;
    }
    private TableRowGroup tableRowGroup1 = new TableRowGroup();

    public TableRowGroup getTableRowGroup1() {
        return tableRowGroup1;
    }

    public void setTableRowGroup1(TableRowGroup trg) {
        this.tableRowGroup1 = trg;
    }
    private Label lblcod = new Label();

    public Label getLblcod() {
        return lblcod;
    }

    public void setLblcod(Label l) {
        this.lblcod = l;
    }
    private Button button5 = new Button();

    public Button getButton5() {
        return button5;
    }

    public void setButton5(Button b) {
        this.button5 = b;
    }
    private Label res = new Label();

    public Label getRes() {
        return res;
    }

    public void setRes(Label l) {
        this.res = l;
    }
    ////Crea

    // </editor-fold>

    /**
     * <p>Construct a new Page bean instance.</p>
     */
    

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        // java.util.Date fecha = new Date();
       // calendar1.setText(new java.sql.Date(fecha.getTime()));
        //String c="n";
        //setEditar(c);

        try{
            URL url = new URL("http://www.bcb.gob.bo/rss_bcb.php");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            String resultado="";
            while ((line = reader.readLine()) != null ) {
                //resultado=resultado+line;
                //textArea1.setText(resultado);
                 if(line.indexOf("UFV =") != -1)
                 {
                     int e = line.indexOf("UFV =");
                     String r=line;
                     String v=r.substring(e+8, e+15);
                      txtufv.setText(v.replace(',', '.'));
                      break;
                }
            }
            reader.close();
         /*   int i=resultado.indexOf("Bs1");
            if(i!= -1)
           {
               //int r = resultado.indexOf("Bs1");
           String v=resultado.substring(i+2, i+9);
           //res.setText(resultado.indexOf("Bs1"));

           txtufv.setText(v.replace(',', '.'));
           resultado="";
            }*/


        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        lblfecha.setVisible(false);
        modifica.setDisabled(true);
        calendar1.setText(this.getSessionBean1().getFecha());

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("ufv Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>try {

         
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
        
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    //RowKey r=getRowk();
    //String dp=this.activoDataProvider.getValue("COD_UFV",r).toString();
    
           //label3.setText(dp);
        ufvDataProvider.refresh();
        
        label4.setVisible(true);

       
    }
    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
        ufvDataProvider.close();
        empleadosDataProvider.close();
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    public String button1_action() throws NamingException, ParseException, IOException, SQLException {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        if(txtufv.getText()==null)
         {   //if(txtci.getValue().toString()==null)
            error("no se permite Campo vacio");}
            else{
                if(calendar1.getText()==null)
                 {
                    error("no se permite Campo vacio");

                 }else{
                   Date cal=calendar1.getSelectedDate();
                    Date calen=new java.sql.Date(cal.getTime());


                 //String ufvs=txtufv.getText().toString();
              //float ufv= Float.valueOf(txtufv.getText().toString().trim()).floatValue();
                String[] params = {"FECHA"};
                Object[] values = {calen};
              
                    ufvDataProvider.cursorFirst();
                    ufvDataProvider.refresh();

                RowKey fila =ufvDataProvider.findFirst("FECHA", calen);
                     if(fila==null){
                        try{

                              boolean valor= insertarufv(txtufv.getValue().toString(),calendar1.getSelectedDate());
                      if(valor==true)
                          error("se inserto correctamente");
//                           getUfvDataProvider().refresh();
                            txtufv.setText("");
                            //label4.setVisible(true);
                     //label4.setValue(valor.toString());

                      }catch (SQLException e)
                            {
                                error(e.getMessage());
                            }
                      }else{
                            error("No se puede insertar dos veces la misma fecha");
                      }

                    }
            }
        return null;
    }
    public boolean insertarufv (String valorufv, Date fecha) throws NamingException, SQLException,ParseException,IOException
    {

     try{
                String dataSourceName=
                       this.getSessionBean1().getUfvRowSet().getDataSourceName();
                 Context ctx= new InitialContext();
                 DataSource ds=(DataSource) ctx.lookup(dataSourceName);

                 CallableStatement cs1 = ds.getConnection().prepareCall("CALL activos.INSERTARUFV(?,?)");

                 float v = Float.valueOf(valorufv.trim()).floatValue();
             cs1.setFloat(1,v);
             cs1.setDate(2,new java.sql.Date(fecha.getTime()));
         
                cs1.executeQuery();

                //label3.setText(new java.sql.Date(fecha.getTime()));
                return true;
     }catch(SQLException e)
            {
                error(e.getMessage());
              
            }
     return false;
    }

    public void buscar_action() throws NamingException, SQLException {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
       if(calendar2.getText()!=null)
       {
        java.util.Date c = new Date();
         c=calendar2.getSelectedDate();     
        String fec=(new java.sql.Date(c.getTime())).toString();
         prueba.setText(fec);
                                              //fecha=to_date(?,'DD-MM-YYYY')                    
        //this.getSessionBean1().ufvRowSet.setCommand("SELECT cod_ufv,valor_ufv,to_char(fecha,'DD-MM-YYYY') as fecha FROM ACTIVOS_FIJOS.UFV where fecha like to_date(?,'YYYY-MM-DD')  order by cod_ufv asc"); 
        //this.getSessionBean1().ufvRowSet.setCommand("select key_ufv, case when key_ufv >= 17 then 'color: #ff3333; font-weight: bold' else 'poco' end  as seleccion from cotizacion order by key_ufv asc");
        this.getSessionBean1().ufvRowSet.setCommand("SELECT key_ufv,ufv,to_char(fecha,'DD-MM-YYYY') as fecha FROM ACTIVOS.COTIZACION where fecha like to_date(?,'YYYY-MM-DD')  order by key_ufv asc");
         this.getSessionBean1().ufvRowSet.setString(1,fec);
        txtufv.setText("");
        calendar1.setText("");
        table1.setVisible(true);
        lblcod.setText("");
        
        ufvDataProvider.refresh();
       }else
       {
           this.getSessionBean1().ufvRowSet.setCommand("SELECT key_ufv,ufv,to_char(fecha,'DD-MM-YYYY') as fecha FROM ACTIVOS.COTIZACION");
           ufvDataProvider.refresh();
           error ("no se permite campo vacio");  }

    }

    public String modifica_action() throws NamingException, ParseException, IOException {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        if(txtufv.getText()=="")
            error("no se permite campo vacio");
        else if(txtufv.getText()==null)
         {   //if(txtci.getValue().toString()==null)
            error("no se permite Campo vacio");}
            else{
                if(calendar1.getText()==null)
                 {
                    error("no se permite Campo vacio");

                 }else{
                        try{

                            boolean valor= actualizaufv(lblcod.getValue().toString(),txtufv.getValue().toString(),calendar1.getSelectedDate());
                      if(valor==true)
                          error("se actualizo correctamente");
//                           getUfvDataProvider().refresh();
                            txtufv.setText("");
                            calendar1.setVisible(true);
                            calendar1.setText("");
                            lblcod.setText("");
                            lblfecha.setVisible(false);
                            ufvDataProvider.refresh();
                            //table1.setVisible(false);
                            //label4.setVisible(true);
                     //label4.setValue(valor.toString());

                      }catch (SQLException e)
                            {
                                error(e.getMessage());
                            }
                    }
            }
        return null;
    }
     public boolean actualizaufv (String codufv, String valorufv, Date fecha) throws NamingException, SQLException,ParseException,IOException
    {
        
     try{
                String dataSourceName=
                        this.getSessionBean1().getUfvRowSet().getDataSourceName();
                 Context ctx= new InitialContext();
                 DataSource ds=(DataSource) ctx.lookup(dataSourceName);

                 CallableStatement cs1 = ds.getConnection().prepareCall("CALL activos.UPDATEUFV(?,?,?)");
                  int cod=Integer.parseInt(codufv);
                  cs1.setInt(1,cod);                 
                 float v = Float.valueOf(valorufv.trim()).floatValue();
             cs1.setFloat(2,v);
             cs1.setDate(3,new java.sql.Date(fecha.getTime()));

                cs1.executeQuery();
                //label3.setText(new java.sql.Date(fecha.getTime()));
                 
                button1.setDisabled(false);
                modifica.setDisabled(true);
                return true;
     }catch(SQLException e)
            {
                error(e.getMessage());

            }
     return false;
    }

    public void button2_action() {
        button1.setDisabled(false);
        modifica.setDisabled(true);
        txtufv.setText("1");
        txtufv.setDisabled(true);
        txtufv.setDisabled(false);
        txtufv.setText("");
        //calendar1.setVisible(true);
        lblfecha.setVisible(false);
        //calendar1.setText("");
     String year=calendar1.getSelectedDate().toString();
     String ye=year.substring(1,16);
     res.setText(ye);
       // return null;
    }

    private RowKey row=new RowKey();
    public void setRowk(RowKey r){
        this.row=r;
    }
    
    public RowKey getRowk() {
        return row;
    }

    public void button4_action() throws SQLException, ParseException {
        RowKey rk = tableRowGroup1.getRowKey();
        setRowk(rk);
        String dp=ufvDataProvider.getValue("KEY_UFV",rk).toString();
            aux=dp;
        //activosRowSet.setString(1,dp);
         String vufv= ufvDataProvider.getValue("UFV",rk).toString();                      
        String date=ufvDataProvider.getValue("FECHA",rk).toString();
        //activosRowSet.setString(1,aux);
        //activosRowSet.setString(1, date);
        //activosRowSet.setDate(1,new java.sql.Date(date.getTime()));
       

        this.getSessionBean1().setcv(dp.toString());


        lblcod.setText(dp);
        txtufv.setText(vufv);
        lblfecha.setText(date);
        calendar1.setText(date);
        calendar1.setVisible(false);
        lblfecha.setVisible(true);
        //label4.setText(dp);       
        button1.setDisabled(true);
        modifica.setDisabled(false);
       //activoDataProvider.refresh();
       // return null;
    }

    public void txtufv_validate(FacesContext fc, UIComponent component, Object o) {

        String strValue = String.valueOf(o);
  if (!strValue.matches(".+@.+\\.[a-z]+")) {
   ResourceBundle resourceBundle = ResourceBundle.getBundle(
                             "literales.ErroresBundle",
                             fc.getViewRoot().getLocale());
   String strTextoError = resourceBundle.getString("error_email_incorrecto");
   throw new ValidatorException(new FacesMessage(strTextoError));
  }
    }

    public String button5_action() throws NamingException {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
       ResultSet rs = null;
        Date fecha= calendar2.getSelectedDate();
        try{
                String dataSourceName=
                        this.getSessionBean1().getUfvRowSet().getDataSourceName();
                 Context ctx= new InitialContext();
                 DataSource ds=(DataSource) ctx.lookup(dataSourceName);

                 //CallableStatement cs1 = ds.getConnection().prepareCall("select *from ufv where fecha like to_date(?,'DD-MM-YYYY')");
                 CallableStatement cs1 = ds.getConnection().prepareCall("select valor_ufv from ufv");
             //cs1.setDate(1,new java.sql.Date(fecha.getTime()));

               rs= cs1.executeQuery();
                //label3.setText(new java.sql.Date(fecha.getTime()));
                //String a[]=null;
                int i=0,j=1;
                //Object [] fila = new Object[10];

                List<String> list = new ArrayList<String>();

                  while(rs.next()){
                        //Array b=rs.getArray("valor_ufv");
                         //listbox1.setItems(a);
                      //fila[i]=rs.getObject("valor_ufv");
                      //listbox1.setItems(a);
                           list.add(rs.getString("valor_ufv"));
                           
                           listbox1.setItems(list.get(i));
                    //i++;
                         //listbox1.setItems(new String[] {"one", "two", "three"});
                        //res.setText(rs.getObject("valor_ufv"));
                         //listbox1.setWidth("40%");
                  }

                CallableStatement cs2 = ds.getConnection().prepareCall("DECLARE tx_values value_array := value_array ('Valor 1', 'Valor 2', 'Valor 3'); BEGIN prueba (tx_values); END; ");
                           cs2.setArray(1, (Array) list);
                           cs2.executeQuery();
                  /*else
                  {
                        res.setText("no hay datos");
                  }*/
                button1.setDisabled(false);
                modifica.setDisabled(true);
                
     }catch(SQLException e)
            {
                error(e.getMessage());

            }
        
        return null;
    }

    public String actualizar_ufv_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        
        
        return null;
    }

    public void lkufv_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        try{
                        FacesContext contex = FacesContext.getCurrentInstance();
                        contex.getExternalContext().redirect( "/SistemaBienes/faces/ufv.jsp" );

            }catch(  Exception e ){
             error( " no funciona esta redireccion" );
                }
    }

    
    
}